package server

import (
	"context"

	pb "kratos-layout/api/helloworld/v1"
	"kratos-layout/app/helloworld/internal/conf"
	"kratos-layout/app/helloworld/internal/service"
	"kratos-layout/pkg/jwt/claim"
	"kratos-layout/pkg/pprof"
	"kratos-layout/pkg/response"
	"kratos-layout/pkg/utils"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/auth/jwt"
	"github.com/go-kratos/kratos/v2/middleware/logging"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/selector"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/middleware/validate"
	"github.com/go-kratos/kratos/v2/transport/http"
	"github.com/go-kratos/swagger-api/openapiv2"
	jwtv4 "github.com/golang-jwt/jwt/v4"
	"github.com/gorilla/handlers"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

// NewHTTPServer new an HTTP server.
func NewHTTPServer(
	c *conf.Server,
	logger log.Logger,
	// generated start
	greeter *service.GreeterService,
	// generated end
) *http.Server {
	var opts = []http.ServerOption{
		http.Middleware(
			recovery.Recovery(),
			validate.Validator(),
			tracing.Server(),
			logging.Server(logger),
			selector.Server(
				jwt.Server(func(token *jwtv4.Token) (interface{}, error) {
					return []byte(c.Jwt.Secret), nil
				},
					jwt.WithSigningMethod(jwtv4.SigningMethodHS256),
					jwt.WithClaims(func() jwtv4.Claims {
						return claim.NewCustomClaims()
					})),
			).Match(NewWhiteListMatcher()).Build(),
		),
		http.ResponseEncoder(response.ResponseEncoder),
		http.ErrorEncoder(response.ErrorEncoder(pb.ErrorReason_value)),
		http.Filter(handlers.CORS(
			handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}),
			handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"}),
			handlers.AllowedOrigins([]string{"*"}),
		)),
	}
	if c.Http.Network != "" {
		opts = append(opts, http.Network(c.Http.Network))
	}
	if c.Http.Addr != "" {
		opts = append(opts, http.Address(c.Http.Addr))
	}
	if c.Http.Timeout != nil {
		opts = append(opts, http.Timeout(c.Http.Timeout.AsDuration()))
	}
	srv := http.NewServer(opts...)
	if c.EnableSwagger {
		h := openapiv2.NewHandler()
		srv.HandlePrefix("/q/", h)
	}
	if c.EnablePprof {
		p := pprof.NewHandler("")
		srv.HandlePrefix("/debug/", p)
	}
	if c.EnableMetrics {
		srv.Handle("/metrics", promhttp.Handler())
	}
	// 额外路由
	// route := srv.Route("/")

	// generated start
	pb.RegisterGreeterHTTPServer(srv, greeter)
	// generated end
	_ = utils.PrintRoutes(srv)
	return srv
}

// NewWhiteListMatcher 白名单不需要token验证的接口
func NewWhiteListMatcher() selector.MatchFunc {
	whiteList := make(map[string]struct{})
	whiteList["/api.helloworld.v1.System/Ping"] = struct{}{}
	whiteList["/api.helloworld.v1.Greeter/SayHello"] = struct{}{}
	return func(ctx context.Context, operation string) bool {
		if _, ok := whiteList[operation]; ok {
			return false
		}
		return true
	}
}
